#include "al_additem.h"
#include "ui_al_additem.h"

AL_AddItem::AL_AddItem(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AL_AddItem)
{
    ui->setupUi(this);

    table=TD_ASSEMBLE_LOG;
    ui->dateEdit->setDate(QDate::currentDate());
    updateProviders();
    updateUnits();
}

AL_AddItem::~AL_AddItem()
{
    delete ui;
}

void AL_AddItem::updateProviders()
{
    QStringList providers=sp_getCategory("provider",table);
    if(!providers.isEmpty())
    {
        ui->providers->addItems(providers);
        ui->providers->setCurrentIndex(-1);
    }
}

void AL_AddItem::updateUnits()
{
    QStringList items=sp_getCategory("name",table);
    if(!items.isEmpty())
    {
        ui->units->addItems(items);
        ui->units->setCurrentIndex(-1);
    }
}

bool AL_AddItem::addItem(const QString &provider,
                         const QString &name,
                         int number,
                         const QString &remark)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (month_,date_,provider,name,number,remark)"
                          " values (?,?,?,?,?,?)")
                  .arg(table));
    query.addBindValue(ui->dateEdit->date().toString(MONTH_FORMAT));
    query.addBindValue(ui->dateEdit->date().toString(DATE_FORMAT));
    query.addBindValue(provider);
    query.addBindValue(name);
    query.addBindValue(number);
    query.addBindValue(remark);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void AL_AddItem::on_providers_currentTextChanged(const QString &text)
{
    ui->provider->setText(text);
}

void AL_AddItem::on_btn_submit_clicked()
{
    QString provider=ui->provider->text().trimmed();
    QString name=ui->units->currentText().trimmed();
    if(provider.isEmpty() || name.isEmpty())
        return;

    QString numStr=ui->number->text().trimmed();
    if(numStr.isEmpty())
        return;

    int number=numStr.toInt();
    if(number == 0)
        return;
    QString remark=ui->remark->text().trimmed();
    if(addItem(provider,name,number,remark))
    {
        if(ui->isMulti->isChecked())
        {
            ui->units->setCurrentIndex(-1);
            ui->number->clear();
            ui->remark->clear();
            emit accepted();
        }
        else
            accept();
    }
    else
        MESSAGE_CANNOT_SUBMIT
}

void AL_AddItem::on_isMulti_stateChanged(int state)
{
    if(state == Qt::Checked)
    {
        ui->providers->setEnabled(false);
        ui->provider->setEnabled(false);
    }
    else
    {
        ui->providers->setEnabled(true);
        ui->provider->setEnabled(true);
    }
}
